package com.example.flutter_ad_demo

import android.app.Activity
import android.app.Dialog
import android.app.ProgressDialog
import android.util.Log
import com.bwt.top.AdUtil
import com.bwt.top.NativeAd
import com.bwt.top.NativeAdListener
import com.bwt.top.ad.bean.NativeAdInfo
import com.bwt.top.exception.AdError

/**
 * 热启动广告管理器
 */
class InterstitialAdManager private constructor() {
    companion object {
        private const val TAG = "InterstitialAdManager"

        @JvmField
        val instance = InterstitialAdManager()
    }

    private var nativeAd: NativeAd? = null
    private var nativeAdInfo: NativeAdInfo? = null
    private var loadingDialog: Dialog? = null

    /**
     * 检查并加载展示热启动插屏广告
     */
    fun showInterstitialAd(activity: Activity) {
        if (activity.isFinishing) return

        // 其他相关的配置请参考文档
        nativeAd = NativeAd(activity)
        // TODO 替换成自己的广告位ID
        nativeAd?.setAdId("24687946")

        nativeAd?.adListener = object : NativeAdListener() {
            override fun onAdReceive(adInfoList: MutableList<NativeAdInfo>?) {
                releaseLoading()

                val ctx = nativeAd?.context
                if (ctx is Activity && !ctx.isFinishing) {
                    nativeAdInfo = adInfoList?.firstOrNull() ?: return

                    // 其他相关的配置请参考文档
                    // 设置插屏广告是否可以按返回键关闭广告
                    AdUtil.setCancelable(true)
                    // 信息流广告 作为插屏形式展示
                    AdUtil.showNativeAdConvenient(ctx, nativeAdInfo, true, this)
                }
            }

            override fun onAdExpose(adInfo: NativeAdInfo?) {
                Log.d(TAG, "广告曝光")
            }

            override fun onAdClick(adInfo: NativeAdInfo?, p1: String?) {
                Log.d(TAG, "广告被点击")
            }

            override fun onAdClick(adInfo: NativeAdInfo?) {
                Log.d(TAG, "广告被点击")
            }

            override fun onAdFailed(adInfo: AdError?) {
                Log.d(TAG, "广告加载失败")
                releaseAd()
            }

            override fun onRenderFailed(adInfo: NativeAdInfo?, p1: AdError?) {
                Log.d(TAG, "广告渲染失败")
                releaseAd()
            }

            override fun onAdClose(adInfo: NativeAdInfo?) {
                Log.d(TAG, "广告关闭")
                releaseAd()
            }
        }

        loadingDialog = ProgressDialog.show(activity, "", "Loading")
        loadingDialog?.show()

        nativeAd?.loadAd()
    }

    /**
     * 释放插屏广告
     */
    private fun releaseAd() {
        try {
            releaseLoading()

            nativeAdInfo?.release()
            nativeAdInfo = null

            nativeAd?.adListener = null
            nativeAd = null
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }

    /**
     * 释放加载中弹框
     */
    private fun releaseLoading() {
        loadingDialog?.dismiss()
        loadingDialog = null
    }

}